package GUI;

import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Toolkit;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;

import model.Client;
import control.*;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.RowFilter;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import java.awt.Color;

public class clients extends JFrame {

	private final TableRowSorter<TableModel> sorter;
	private JPanel contentPane;
	private JTextField tfCcvr;
	private JTextField tfCname;
	private JTextField tfCaddress;
	private JTextField tfCzipCode;
	private JTextField tfCcity;
	private JTextField tfCphone;
	private JTextField tfCgsm;
	private JTextField tfCemail;
	private JTable clientTable;
    private PersonCtrl personCtrl = new PersonCtrl();
    private clientTable clientT = new clientTable();
    private ClientCtrl clientCtrl = new ClientCtrl();
    private JTextField tfCcontactCpr;
    private JTextField tfSearch;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					clients frame = new clients();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public clients() {
		setIconImage(Toolkit.getDefaultToolkit().getImage("C:\\Users\\Andrada\\Desktop\\images.jpg"));
		setTitle("CLIENTS");
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setBounds(100, 100, 1050, 600);
		contentPane = new JPanel();
		contentPane.setBackground(new Color(255, 255, 153));
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(10, 81, 692, 470);
		contentPane.add(scrollPane);
		
		clientTable = new JTable();
		clientTable.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][]{},
                new String []
                {
                            "Name", "Address", "Zipcode", "City", "Phone", "GSM", "E-mail", "CVR", "Contact CPR"
                }));
		sorter = new TableRowSorter<TableModel>(clientT);
		clientTable.setRowSorter(sorter);
		scrollPane.setViewportView(clientTable);
		
		JLabel lblListOfClients = new JLabel("LIST OF CLIENTS");
		lblListOfClients.setHorizontalAlignment(SwingConstants.CENTER);
		lblListOfClients.setFont(new Font("Times New Roman", Font.BOLD, 15));
		lblListOfClients.setBounds(10, 7, 692, 31);
		contentPane.add(lblListOfClients);
		
		JPanel clientPanel = new JPanel();
		clientPanel.setBackground(new Color(255, 255, 153));
		clientPanel.setLayout(null);
		clientPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Client Control", TitledBorder.CENTER, TitledBorder.TOP, null, null));
		clientPanel.setBounds(712, 50, 312, 501);
		contentPane.add(clientPanel);
		
		JLabel lblCcvr = new JLabel("CVR :");
		lblCcvr.setHorizontalAlignment(SwingConstants.RIGHT);
		lblCcvr.setFont(new Font("Times New Roman", Font.PLAIN, 15));
		lblCcvr.setBounds(6, 16, 114, 31);
		clientPanel.add(lblCcvr);
		
		tfCcvr = new JTextField();
		tfCcvr.setColumns(10);
		tfCcvr.setBounds(130, 20, 170, 25);
		clientPanel.add(tfCcvr);
		
		JLabel lblCname = new JLabel("Name :");
		lblCname.setHorizontalAlignment(SwingConstants.RIGHT);
		lblCname.setFont(new Font("Times New Roman", Font.PLAIN, 15));
		lblCname.setBounds(6, 58, 114, 31);
		clientPanel.add(lblCname);
		
		JLabel lblCaddress = new JLabel("Address :");
		lblCaddress.setHorizontalAlignment(SwingConstants.RIGHT);
		lblCaddress.setFont(new Font("Times New Roman", Font.PLAIN, 15));
		lblCaddress.setBounds(6, 100, 114, 31);
		clientPanel.add(lblCaddress);
		
		tfCname = new JTextField();
		tfCname.setColumns(10);
		tfCname.setBounds(130, 62, 170, 25);
		clientPanel.add(tfCname);
		
		tfCaddress = new JTextField();
		tfCaddress.setColumns(10);
		tfCaddress.setBounds(130, 104, 170, 25);
		clientPanel.add(tfCaddress);
		
		JLabel lblCzipCode = new JLabel("Zip Code :");
		lblCzipCode.setHorizontalAlignment(SwingConstants.RIGHT);
		lblCzipCode.setFont(new Font("Times New Roman", Font.PLAIN, 15));
		lblCzipCode.setBounds(6, 142, 114, 31);
		clientPanel.add(lblCzipCode);
		
		JLabel lblCcity = new JLabel("City :");
		lblCcity.setHorizontalAlignment(SwingConstants.RIGHT);
		lblCcity.setFont(new Font("Times New Roman", Font.PLAIN, 15));
		lblCcity.setBounds(6, 184, 114, 31);
		clientPanel.add(lblCcity);
		
		JLabel lblCphone = new JLabel("Phone :");
		lblCphone.setHorizontalAlignment(SwingConstants.RIGHT);
		lblCphone.setFont(new Font("Times New Roman", Font.PLAIN, 15));
		lblCphone.setBounds(6, 226, 114, 31);
		clientPanel.add(lblCphone);
		
		JLabel lblCgsm = new JLabel("GSM :");
		lblCgsm.setHorizontalAlignment(SwingConstants.RIGHT);
		lblCgsm.setFont(new Font("Times New Roman", Font.PLAIN, 15));
		lblCgsm.setBounds(6, 268, 114, 31);
		clientPanel.add(lblCgsm);
		
		JLabel lblCemail = new JLabel("Email :");
		lblCemail.setHorizontalAlignment(SwingConstants.RIGHT);
		lblCemail.setFont(new Font("Times New Roman", Font.PLAIN, 15));
		lblCemail.setBounds(6, 310, 114, 31);
		clientPanel.add(lblCemail);
		
		tfCzipCode = new JTextField();
		tfCzipCode.setColumns(10);
		tfCzipCode.setBounds(130, 146, 170, 25);
		clientPanel.add(tfCzipCode);
		
		tfCcity = new JTextField();
		tfCcity.setColumns(10);
		tfCcity.setBounds(130, 188, 170, 25);
		clientPanel.add(tfCcity);
		
		tfCphone = new JTextField();
		tfCphone.setColumns(10);
		tfCphone.setBounds(130, 230, 170, 25);
		clientPanel.add(tfCphone);
		
		tfCgsm = new JTextField();
		tfCgsm.setColumns(10);
		tfCgsm.setBounds(130, 272, 170, 25);
		clientPanel.add(tfCgsm);
		
		tfCemail = new JTextField();
		tfCemail.setColumns(10);
		tfCemail.setBounds(130, 314, 170, 25);
		clientPanel.add(tfCemail);
		
		clientTable.addMouseListener(new MouseAdapter() {
      	  public void mouseClicked(MouseEvent e) {
      	    if (e.getClickCount() == 2) {
      	      JTable target = (JTable)e.getSource();
      	      int row = target.getSelectedRow();
      	      setClientFields((String)clientTable.getModel().getValueAt(row, 7));
      	    }
      	  }
      	});
		
		JButton btnCadd = new JButton("Add");
		btnCadd.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(ifEmpty()) return;
                if(ifClientExists())
        		{
        			JOptionPane.showMessageDialog(null,"Client with this CVR already exists.");
        			return;
        		}
                if(ifContactExists() == false)
                {
                	JOptionPane.showMessageDialog(null,"Contact with this CPR does not exist.");
        			return;
                }
                try 
                {
                        clientCtrl.createClient(tfCcvr.getText(), tfCname.getText(), tfCaddress.getText(), tfCzipCode.getText(), tfCcity.getText(),
                                                 tfCphone.getText(), tfCgsm.getText(), tfCemail.getText(), tfCcontactCpr.getText());
                        updateClientTable();
                        clearTextFields();
                        JOptionPane.showMessageDialog(null,"Client has been successfuly created.");
                } 
                catch (Exception r) 
                {
                        JOptionPane.showMessageDialog(null,"Error in creating Client.");
                }
			}
		});
		btnCadd.setFont(new Font("Times New Roman", Font.BOLD, 17));
		btnCadd.setBounds(10, 459, 90, 31);
		clientPanel.add(btnCadd);
		
		JButton btnCupdate = new JButton("Update");
		btnCupdate.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(ifEmpty()) return;
    			if(ifClientExists() == false)
        		{
        			JOptionPane.showMessageDialog(null,"Client with this CVR does not exist.");
        			return;
        		}
    			if(ifContactExists() == false)
                {
                	JOptionPane.showMessageDialog(null,"Contact with this CPR does not exist.");
        			return;
                }
    			try
    			{
    				clientCtrl.updateClient(tfCcvr.getText(), tfCname.getText(), tfCaddress.getText(), tfCzipCode.getText(), tfCcity.getText(),
                                             tfCphone.getText(), tfCgsm.getText(), tfCemail.getText(), tfCcontactCpr.getText());
    				updateClientTable();
    				clearTextFields();
                    JOptionPane.showMessageDialog(null,"Client has been successfuly updated.");
    			}
    			catch(Exception r)
    			{
    				JOptionPane.showMessageDialog(null,"Error in updating Client.");
    			}
			}
		});
		btnCupdate.setFont(new Font("Times New Roman", Font.BOLD, 17));
		btnCupdate.setBounds(110, 459, 90, 31);
		clientPanel.add(btnCupdate);
		
		JButton btnCdelete = new JButton("Delete");
		btnCdelete.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(ifClientExists() == false)
        		{
        			JOptionPane.showMessageDialog(null,"Client with this CVR does not exist.");
        			return;
        		}
                try
                {
                	if(clientCtrl.deleteClient(tfCcvr.getText()))
                     	JOptionPane.showMessageDialog(null,"Client has been successfuly deleted.");
                    else
                     	JOptionPane.showMessageDialog(null,"Cannot delete client.");    ;
                        updateClientTable();
                        clearTextFields();
                }
                catch(Exception r)
                {
                        JOptionPane.showMessageDialog(null,"Error in deleting Client.");
                }
			}
		});
		btnCdelete.setFont(new Font("Times New Roman", Font.BOLD, 17));
		btnCdelete.setBounds(210, 459, 90, 31);
		clientPanel.add(btnCdelete);
		
		tfCcontactCpr = new JTextField();
		tfCcontactCpr.setColumns(10);
		tfCcontactCpr.setBounds(130, 356, 170, 25);
		clientPanel.add(tfCcontactCpr);
		
		JLabel lblCcontactCpr = new JLabel("Contact CPR:");
		lblCcontactCpr.setHorizontalAlignment(SwingConstants.RIGHT);
		lblCcontactCpr.setFont(new Font("Times New Roman", Font.PLAIN, 15));
		lblCcontactCpr.setBounds(6, 352, 114, 31);
		clientPanel.add(lblCcontactCpr);
		
		JLabel lblManageClients = new JLabel("MANAGE CLIENTS");
		lblManageClients.setHorizontalAlignment(SwingConstants.CENTER);
		lblManageClients.setFont(new Font("Times New Roman", Font.BOLD, 15));
		lblManageClients.setBounds(712, 7, 312, 31);
		contentPane.add(lblManageClients);
		
		JLabel lblSearch = new JLabel("Search :");
		lblSearch.setBounds(10, 42, 110, 30);
		contentPane.add(lblSearch);
		lblSearch.setHorizontalAlignment(SwingConstants.RIGHT);
		lblSearch.setFont(new Font("Times New Roman", Font.PLAIN, 15));
		
		tfSearch = new JTextField();
		tfSearch.setBounds(130, 45, 130, 25);
		contentPane.add(tfSearch);
		tfSearch.setColumns(10);
		tfSearch.getDocument().addDocumentListener(new DocumentListener() {  // <---
            @Override
            public void removeUpdate(DocumentEvent e) {
                filter();
            }
             
            @Override
            public void insertUpdate(DocumentEvent e) {
                filter();
            }
             
            @Override
            public void changedUpdate(DocumentEvent e) {}
        });
	}
	
	public void setClientFields(String cvr)
    {
    	 Client client = clientCtrl.getClientByCvr(cvr);
    	 tfCcvr.setText(client.getCvr());
         tfCname.setText(client.getName());
         tfCaddress.setText(client.getAddress());
         tfCzipCode.setText(client.getZipCode());
         tfCcity.setText(client.getCity());
         tfCphone.setText(client.getPhone());
         tfCgsm.setText(client.getGsm());
         tfCemail.setText(client.getEmail());
         tfCcontactCpr.setText(client.getContact().getCpr());
    }
	
	public boolean ifEmpty()
    {
            if(tfCcvr.getText().equals("") || tfCname.getText().equals("") || tfCaddress.getText().equals("") || tfCzipCode.getText().equals("") ||
              tfCcity.getText().equals("") || tfCphone.getText().equals("") || tfCgsm.getText().equals("") || tfCemail.getText().equals("") || tfCcontactCpr.getText().equals(""))
            {
                    JOptionPane.showMessageDialog(null,"Some of the fields are empty.");
                    return true;
            }
            return false;
    }
	
	public boolean ifClientExists()
    {
    	if(clientCtrl.getClientByCvr(tfCcvr.getText()) != null)
    		return true;
    	return false;
    }
	
	public boolean ifContactExists()
    {
    	if(personCtrl.getContactByCpr(tfCcontactCpr.getText()) != null)
    		return true;
    	return false;
    }
	
	 public void clearTextFields()
     {
             tfCcvr.setText("");
             tfCname.setText("");
             tfCaddress.setText("");
             tfCzipCode.setText("");
             tfCcity.setText("");
             tfCphone.setText("");
             tfCgsm.setText("");
             tfCemail.setText("");
             tfCcontactCpr.setText("");
     }
	 
	 public void updateClientTable()
     {
     clientT.setClient(clientCtrl.listAllClients());
     clientTable.setModel(clientT);
     }
	 
	 protected void filter()
	 {
		 sorter.setRowFilter(RowFilter.regexFilter("^(?i)"+tfSearch.getText()));
	 }
}
